<template>
  <div>
    <div>
      <el-page-header class="chat-header" content="主页" @back="goBack"></el-page-header>
    </div>
    <div class="chat-con" ref="contentArea">
        <div v-for="(msgItem, index) in msgList" :key="index" class="msg-item">
        <!--          //消息-->
          <div :style="{float: msgItem.type === 'other' ? 'left' : 'right',}">
        <!--        头像    //-->
            <div :style="{float: msgItem.type === 'other' ? 'left' : 'right', margin: '10px',textAlign: 'center',}">
              <el-avatar
                  :size="40"
                  :src="msgItem.avatar"
                  style="display: block"
              ></el-avatar>
              <span style="font-size: 12px">{{ msgItem.userName }}</span>
            </div>
<!--            //消息-->
            <el-card
                class="box-card"
                style="margin: 0 10px"
                :style="{
                float: msgItem.type === 'other' ? 'left' : 'right',
              }"
            >
              <span v-if="msgItem.msg.type === 'text'">{{ msgItem.msg.content }}</span>
              <el-image v-else :src="msgItem.msg.content"></el-image>
            </el-card>
          </div>
        </div>
    </div>
    <div class="chat-footer">
      <el-row >
        <el-col :span="1" style="position: relative;text-align: center">
          <input
              type="file"
              ref="selectImg"
              @change="sendImg"
              style="position:absolute;top: 0;left: 0; opacity: 0">
          <i class="el-icon-s-marketing" style="font-size: 40px"></i>
        </el-col>
        <el-col :span="20" style="text-align: center">
          <el-input v-model="msgText" placeholder="请输入消息" @keydown.native.enter="sendText"></el-input>
        </el-col>
        <el-col :span="3" style="padding-left: 11px">
          <el-button type="primary" icon="el-icon-s-promotion" @click="sendText">发送</el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import defaultConfig from "@/config/config.default";
async function imgToBase64(files,width,quality){
  return new Promise((resolve)=>{
    //处理图片信息
    let file=files[0]
    let img=new Image()
    let URL = window.URL || window.webkitURL;
    let imgUrl= URL.createObjectURL(file);
    img.src=imgUrl
    let base64
    img.onload=function (){
      const that = this;
      let w = that.width;
      let h = that.height;
      let scale = w / h;
      w = width || w;
      h = w / scale;
      const canvas = document.createElement("canvas");
      const canCon = canvas.getContext("2d");
      canvas.width = w;
      canvas.height = h;
      canCon.drawImage(that, 0, 0, w, h);
      base64 = canvas.toDataURL("image/jpeg", quality || 0.5);
      resolve(base64);
    }
  })
}
export default {
  name: "Chathome",
  data(){
    return {
      socket: null,
      msgText: "",
      message: {
        userName: "",
        avatar: "",
        msg: {
          type: "",//区分消息的类型 图片 文字
          content: "",
        },
        //存在type //区分发送的人
      },
      userData: JSON.parse(sessionStorage.getItem("userData")),
      msgList: [],
    }
  },
  watch: {
    userData: {
      handler() {
        this.message.userName = this.userData.userName;
        this.message.avatar = this.userData.avatar;
      },
      immediate: true,
    },
  },
  mounted() {
    //穿创建连接
    this.socket = new WebSocket(`${defaultConfig.wssApiUrl}`);
    let vm = this;
    this.socket.addEventListener("open", function () {
      vm.$message.success("加入聊天室");
    });
    this.socket.addEventListener("message",function (event){
      //接受广播信息
      vm.msgList.push({
        ...JSON.parse(event.data),
        type:"other"
      })
      vm.$nextTick(function () {
        console.log(vm.$refs.contentArea.scrollHeight)
        vm.$refs.contentArea.scrollTop = vm.$refs.contentArea.scrollHeight;
      });
    })
  },
  methods: {
    // 改变滚动条

    goBack() {
      this.$router.go(-1)
    },
    sendImg(){
      //进行图片转为base64 canva压缩
      imgToBase64(this.$refs['selectImg'].files,400).then(res=>{

        //收集数据 发送过去
        this.message.msg.type="image"
        this.message.msg.content=res
        this.socket.send(JSON.stringify(this.message))
        //初始化
        this.msgText = "";
        this.msgList.push({
          ...JSON.parse(JSON.stringify(this.message)),
          type: "me",
        });
        this.message.msg.type = "";
        this.message.msg.content = "";
        this.$nextTick(()=>{
          this.$refs.contentArea.scrollTop = this.$refs.contentArea.scrollHeight;
        })
      })

    },

    sendText(){
      if (this.msgText){
        //收集数据 发送过去
        this.message.msg.type="text"
        this.message.msg.content=this.msgText
        this.socket.send(JSON.stringify( this.message))
        //初始化
        this.msgText = "";
        this.msgList.push({
          ...JSON.parse(JSON.stringify(this.message)),
          type: "me",
        });
        this.message.msg.type = "";
        this.message.msg.content = "";
        this.$nextTick(()=>{
          this.$refs.contentArea.scrollTop = this.$refs.contentArea.scrollHeight;
        })
      }
    }
  }
}
</script>

<style>
body {
  margin: 0;
  padding: 0;
}

.chat-header {
  height: 50px;
  line-height: 50px;
}

.chat-con {
  background: pink;
  height: calc(100vh - 90px);
  overflow-x: hidden;
  overflow-y: scroll;
}
.chat-footer{
  height: 40px;
}
.msg-item{
  margin-bottom: 14px;
}
.msg-item::after {
  content: "";
  display: block;
  clear: both;
}
</style>